<template>
    <div class="default-main">
        
          
                <div class="config-info">
                    <!-- <el-upload
                        class="avatar-uploader"
                        action=""
                        :show-file-list="false"
                        @change="onAvatarBeforeUpload"
                        :auto-upload="false"
                        accept="image/gif, image/jpg, image/jpeg, image/bmp, image/png, image/webp"
                        v-if="!isEmpty(state.adminInfo)"
                    >
                        <el-image fit="cover" :src="fullUrl(state.adminInfo.avatar)" class="avatar">
                            <template #error>
                                <div class="image-slot">
                                    <Icon size="30" color="#c0c4cc" name="el-icon-Picture" />
                                </div>
                            </template>
                        </el-image>
                    </el-upload> -->
       
                    <div class="config-info-form">
                        <el-form
                            @keyup.enter="onSubmit()"
                            key="key"
                            label-position="top"
                            :rules="rules"
                            ref="formRef"
                            :model="items"
                            class="form-box"  label-width="120px"
                        >
                        <div style="width: 240px;">
                        <FormItem label="单超时时间（分钟）" type="number" 
                        v-model.number="items.timeout" 
                        :input-attr="{ clearable: true, size: 'large' }" />
                        </div>
                            <FormItem
                                label="账单冲突解决方案"
                                type="radio"
                                v-model.number="items.conflict" 
                                :input-attr="{ size: 'large' }"
                                :data="{ childrenAttr: { border: true }, content: { 1: '金额递增', 2: '金额递减' } }"
                            />

                            <el-form-item :label="t('通讯密钥')" prop="secret_key">
                                <el-input
                                    :placeholder="t('Please input field', { field: t('通讯密钥') })"
                                    v-model="items.secret_key"
                                    style="width: 360px" 
                                    readonly
                                ></el-input>
                                <el-button type="primary" @click="generateKey">生成密钥</el-button>
                            </el-form-item>

                            <el-form-item :label="t('微信收款码')" prop="wechat">
                               <el-upload action="#" 
                               :show-file-list="false"
                                @change="wechatUpload" list-type="picture-card"  :limit="1"  :auto-upload="false">
                                <el-image fit="cover" :src="fullUrl(items.wechat)" class="avatar">
                                    <template #error>
                                        <div class="image-slot">
                                            <Icon size="30" color="#c0c4cc" name="el-icon-Picture" />
                                        </div>
                                    </template>
                                </el-image>
                               </el-upload>
                            </el-form-item>
                        

                            <el-form-item :label="t('支付宝收款码')" prop="alipay">
                               <el-upload action="#" 
                               :show-file-list="false"
                                @change="alipayUpload" list-type="picture-card"  :limit="1"  :auto-upload="false">
                                <el-image fit="cover" :src="fullUrl(items.alipay)" class="avatar">
                                    <template #error>
                                        <div class="image-slot">
                                            <Icon size="30" color="#c0c4cc" name="el-icon-Picture" />
                                        </div>
                                    </template>
                                </el-image>
                               </el-upload>
                            </el-form-item>
                          
                            <el-form-item>
                                <el-button type="primary" :loading="buttonLoading"  @click="onSubmit()">
                                    {{ t('保 存') }}
                                </el-button>
                                <el-button @click="onResetForm(formRef)">{{ t('Reset') }}</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
        
           
       
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormItemRule, UploadRawFile, UploadUserFile,UploadFiles } from 'element-plus'
import { fullUrl, onResetForm, timeFormat } from '/@/utils/common'

import { buildValidatorData } from '/@/utils/validate'
import { fileUpload } from '/@/api/common'
import FormItem from '/@/components/formItem/index.vue'
import QrCodeDecoder from "qrcode-decoder";
import QRCode from 'qrcode'
import { uuid } from '/@/utils/random'
import { edit, index } from '../../../../api/vpay/config'

const { t } = useI18n()
const formRef = ref<FormInstance>()
const qr = new QrCodeDecoder();
let buttonLoading = false
let items = reactive({
    timeout: 3,
    conflict: 1,
    wechat: '',
    alipay: '',
    secret_key: '',
})

onMounted(() => {
    index().then(res => {
        if(res.data){
            items.timeout = res.data.timeout
            items.conflict = res.data.conflict
            items.wechat = res.data.wechat
            items.alipay = res.data.alipay
            items.secret_key = res.data.secret_key
        }
    })
})

const generateKey = () => {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let key = '';
        for (let i = 0; i < 32; i++) {
          key += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        items.secret_key = key;
      };

const wechatUpload = (file: UploadUserFile, files: UploadFiles) => {    
    upload(file, files).then(res => {
        if (res.code == 1) {    
            items.wechat = res.data.file.full_url
        }
    })
}

const alipayUpload = (file: UploadUserFile, files: UploadFiles) => {    
    upload(file, files).then(res => {
        if (res.code == 1) {    
            items.alipay = res.data.file.full_url
        }
    })


}


const upload = (file: UploadUserFile, files: UploadFiles) => {
    return beforeUpload(file).then(newfile => {
        let fd = new FormData()
        fd.append('file', newfile)
        return fileUpload(fd)
    })
}


// 将数据 URL 转换为文件
function dataURLtoFile(dataURL: string, filename: string): File {
    const arr = dataURL.split(",");
    const mime = arr[0].match(/:(.*?);/)![1];
    const bstr = atob(arr[1]);
    const u8arr = new Uint8Array(bstr.length);
    for (let i = 0; i < bstr.length; i++) {
        u8arr[i] = bstr.charCodeAt(i);
    }
    return new File([u8arr], filename, { type: mime });
}

const beforeUpload = (file: UploadRawFile) => {
    return new Promise((resolve, reject) => {
     qr.decodeFromImage(file.url).then((result) => {
        QRCode.toDataURL(result.data, {
        width: 300, // 设置宽度为 300px
        height: 300, // 设置高度为 300px
        margin: 2, // 设置边距为 2px
        type: file?.raw?.type,
        color: {
            dark: "#000000", // 二维码前景色（黑色）
            light: "#ffffff", // 二维码背景色（白色）
        },
    }, (err:Error, url:string) => {
            if (err) throw err;
            resolve(dataURLtoFile(url, file.name));
        });
    })
})
}




const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    timeout: [buildValidatorData({ name: 'required', title: t('单超时时间')})],
    conflict: [buildValidatorData({ name: 'required', title: t('账单冲突解决方案') })],
    wechat: [buildValidatorData({ name: 'required', title: t('微信收款码') })],
    alipay: [buildValidatorData({ name: 'required', title: t('支付宝收款码') })],
    secret_key: [buildValidatorData({ name: 'required', title: t('通讯密钥') })],
})



const onSubmit = () => {
    if (!formRef.value) return
    console.log(formRef.value)
    formRef.value.validate((valid) => {
        console.log('validate')
        console.log(valid)
        if (valid) {
            buttonLoading = true
            edit(items)
            .then(() => {
                buttonLoading = false
            })
            .catch(() => {
                buttonLoading = false
            })
        }
    })
}
</script>

<style scoped lang="scss">
.config-info {
    background-color: var(--ba-bg-color-overlay);
    border-radius: var(--el-border-radius-base);

    .avatar-uploader {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        margin: 60px auto 10px auto;
        border-radius: 50%;
        box-shadow: var(--el-box-shadow-light);
        border: 1px dashed var(--el-border-color);
        cursor: pointer;
        overflow: hidden;
        width: 110px;
        height: 110px;
    }
    .avatar-uploader:hover {
        border-color: var(--el-color-primary);
    }
    .avatar {
        width: 110px;
        height: 110px;
        display: block;
    }
    .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }
    .config-info-base {
        .config-nickname {
            font-size: 22px;
            color: var(--el-text-color-primary);
            text-align: center;
            padding: 8px 0;
        }
        .admin-other {
            color: var(--el-text-color-regular);
            font-size: 14px;
            text-align: center;
            line-height: 20px;
        }
    }
    .config-info-form {
        padding: 30px;
    }
}
.el-card :deep(.el-timeline-item__icon) {
    font-size: 10px;
}
@media screen and (max-width: 1200px) {
    .lg-mb-20 {
        margin-bottom: 20px;
    }
}

</style>
